package com.naxiang.cn.naxiangvideoplay;

import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Toast;

import com.baidu.cloud.media.player.IMediaPlayer;
import com.bumptech.glide.Glide;
import com.naxiang.cn.utils.ItemBeen;
import com.naxiang.cn.widget.BDCloudVideoView;
import com.naxiang.cn.widget.BDCloudVideoView.PlayerState;
import com.uzmap.pkg.uzcore.UZWebView;
import com.uzmap.pkg.uzcore.uzmodule.UZModule;
import com.uzmap.pkg.uzcore.uzmodule.UZModuleContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者: 赵航
 * 创建时间: 2018/7/18 17:34
 * 描述:
 */
public class NaXiangVideo extends UZModule implements IMediaPlayer.OnErrorListener, IMediaPlayer.OnInfoListener, IMediaPlayer.OnBufferingUpdateListener, BDCloudVideoView.OnPlayerStateListener, IMediaPlayer.OnPreparedListener, IMediaPlayer.OnCompletionListener {
    //播放器的
    private RelativeLayout mRela;
    private BDCloudVideoView mVV = null;
    private String mUri;
    private boolean isFull     = false;//是否全屏显示
    private boolean mFllScreen = false;//视频比例和屏幕比例不一致的话，默认不能全屏问题
    private int                   mMaxProbeTime;
    private SimpleMediaController mMediaController;
    private UZModuleContext       mModuleContext;
    private int mLift  = 0; //小屏播放的距离左边的距离
    private int mTop   = 0;//小屏播放的距离上边的距离
    private int mHight = 100;//小屏播放的播放器高度的距离
    private int mWidth = -1;//小屏播放的播放器高度的宽度
    private boolean mFixed; //小屏是否跟着一起滑动
    private String mIndexName = "";//小屏可以加载的布局
    //全屏显示的界面以及是否一起滚动
    private boolean mFllFixed;  //大屏是否跟着一起滚动
    private String  mIndexFullName = "";//大屏索要加载的布局名称
    private boolean isMusic        = false;

    private String  mImageUri      = "";
    //标记侧面是否滑出来
    private boolean mCloseOpen     = false;
    private ObjectAnimator mAnimtion;
    private JSONArray      mVidoeUriList;
    private JSONArray      mImageUriList;
    private List<ItemBeen> itemBeens        = new ArrayList<>();
    private int            mListImageWidth  = 300;
    private int            mListImageHeight = 500;
    private JSONArray mIdList;
    private String mPeoploNumber = "999人在线";
    private int    mId           = -1;
    private String    mTitleText;
    private int       mHandImageUri;
    private JSONArray mTitleTextList;
    private JSONArray mHandImageUriList;
    private boolean isFristPlay = true;

    private int playPress = 0;

    private int errorTime = 0;//记录当前播放错误的次数
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mHandler.removeCallbacksAndMessages(null);
                    break;
                case 2:
                    int currentPosition = mVV.getCurrentPosition();
                    int duration = mVV.getDuration();
                    if (currentPosition > 0 && duration > 0) {
                        long pos = 10000L * currentPosition / duration;
                        mMediaController.seatProgress((int) pos);
                        mMediaController.getSeekBar().setEnabled(true);
                        JSONObject object = new JSONObject();
                        try {
                            object.put("currentposition", currentPosition);
                            object.put("duration", duration);
                            object.put("mId", mId);
                            if (isFull) {
                                object.put("mIsFull", 1);
                            } else {
                                object.put("mIsFull", 2);
                            }
                            //设置为false为不间断的想后台发送数据
                            mModuleContext.success(object, false);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        mMediaController.getReadTime().setText(formatMilliSecond(currentPosition));
                        mMediaController.getAllTime().setText(formatMilliSecond(duration));
                    } else {
                        mMediaController.getSeekBar().setEnabled(false);
                    }
                    break;
            }
        }
    };
    private String mTitleImageUrl;
    private boolean mShowNumber;


    public NaXiangVideo(UZWebView webView) {
        super(webView);
    }

    //TODO：播放器的植入
    public void jsmethod_openVido(UZModuleContext moduleContext) {
        mModuleContext = moduleContext;
        //TODO:初始化ListVIew数据
        mVidoeUriList = moduleContext.optJSONArray("listvoiduri");
        mImageUriList = moduleContext.optJSONArray("listimageuri");
        mTitleTextList = moduleContext.optJSONArray("titleTextList");
        mHandImageUriList = moduleContext.optJSONArray("headimageurlList");
        mIdList = moduleContext.optJSONArray("idList");
        itemBeens.clear();
        if (mImageUriList != null || mImageUriList.length() != 0) {
            for (int i = 0; i < mImageUriList.length(); i++) {
                if (i < mVidoeUriList.length()) {
                    try {
                        ItemBeen been = new ItemBeen();
                        been.setImageUri((String) mImageUriList.get(i));
                        been.setVidoUri((String) mVidoeUriList.get(i));
                        been.setId((String) mIdList.get(i));
                        been.setHandText((String) mTitleTextList.get(i));
                        String Json = (String) mHandImageUriList.get(i);
                        String newJson= Json.replace("'", "\"");
                        JSONObject jsonObject = new JSONObject(newJson);
                        int mVideoType = jsonObject.optInt("videotype");
                        boolean mShowNumber=  jsonObject.optBoolean("shownumber");
                        String mImageUrl=  jsonObject.optString("imageurl");
                        been.setShownumber(mShowNumber);
                        been.setVideotype(mVideoType);
                        been.setImageurl(mImageUrl);
                        System.out.println("等到的数据是==="+mVideoType+"====="+mShowNumber+"==="+mImageUrl);
                        itemBeens.add(been);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        /**
         * 防闪屏
         */
        getContext().getWindow().setFormat(PixelFormat.TRANSLUCENT);
        isFull = false;
        mLift = moduleContext.optInt("lift", 0);
        mTop = moduleContext.optInt("top", 0);
        mHight = moduleContext.optInt("hight", 100);
        mWidth = moduleContext.optInt("width", -1);
        mId = moduleContext.optInt("mId", -1);
        //视频是否随着界面一起滚动
        mFixed = moduleContext.optBoolean("fixed", false);
        //视频比例和屏幕比例不一致的话，默认不进行满屏显示
        mFllScreen = moduleContext.optBoolean("fullScreen", false);
        mIndexName = moduleContext.optString("indexName", "");
        mImageUri = moduleContext.optString("imageuri", "");
        mMaxProbeTime = moduleContext.optInt("maxprobetime", 2000);
        mUri = moduleContext.optString("uri", "http://resource.apicloud.com/video/apicloud3.mp4");
        mListImageWidth = moduleContext.optInt("listImagewidth", 300);
        mListImageHeight = moduleContext.optInt("listImageheight", 500);
        mTitleText = moduleContext.optString("titleText", "标题获取失败");

        //头部标题怎么显示
        mHandImageUri = moduleContext.optInt("videotype", 2);
        //头部图片的背景uri
        mTitleImageUrl = moduleContext.optString("headimageurl", "");
        //是否展示人数
        mShowNumber=moduleContext.optBoolean("shownumber", false);


        //切换大屏时，要不要跟着屏幕一起滑动
        mFllFixed = moduleContext.optBoolean("fixedFull", true);
        //切换大屏的时候要添加到那个布局上
        mIndexFullName = moduleContext.optString("indexFullName", "");
        if (mRela == null) {
            //初始化视频播放器
            mVV = new BDCloudVideoView(getContext());
            mMediaController = new SimpleMediaController(getContext());
            mRela = new RelativeLayout(getContext());
            mRela.setBackgroundColor(Color.BLACK);
        } else {
            mRela.setBackgroundColor(Color.BLACK);
            removeViewFromCurWindow(mRela);
        }
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mWidth, mHight);
        params.setMargins(mLift, mTop, 0, 0);
        insertViewToCurWindow(mRela, params, mIndexName, mFixed);
        initViodView();
    }

    //打开全屏了
    public void jsmethod_openFullVido(UZModuleContext moduleContext) {
        mModuleContext = moduleContext;
        //TODO:初始化ListVIew数据
        mVidoeUriList = moduleContext.optJSONArray("listvoiduri");
        mImageUriList = moduleContext.optJSONArray("listimageuri");
        mTitleTextList = moduleContext.optJSONArray("titleTextList");
        mHandImageUriList = moduleContext.optJSONArray("headimageurlList");
        mIdList = moduleContext.optJSONArray("idList");
        itemBeens.clear();
        if (mImageUriList != null || mImageUriList.length() != 0) {
            for (int i = 0; i < mImageUriList.length(); i++) {
                if (i < mVidoeUriList.length()) {
                    try {
                        ItemBeen been = new ItemBeen();
                        been.setImageUri((String) mImageUriList.get(i));
                        been.setVidoUri((String) mVidoeUriList.get(i));
                        been.setId((String) mIdList.get(i));
                        been.setHandText((String) mTitleTextList.get(i));
                        String Json = (String) mHandImageUriList.get(i);
                        String newJson= Json.replace("'", "\"");
                        JSONObject jsonObject = new JSONObject(newJson);
                        int mVideoType = jsonObject.optInt("videotype");
                        boolean mShowNumber=  jsonObject.optBoolean("shownumber");
                        String mImageUrl=  jsonObject.optString("imageurl");
                        been.setShownumber(mShowNumber);
                        been.setVideotype(mVideoType);
                        been.setImageurl(mImageUrl);

                        System.out.println("等到的数据是==="+mVideoType+"====="+mShowNumber+"==="+mImageUrl);
                        itemBeens.add(been);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        /**
         * 防闪屏
         */
        getContext().getWindow().setFormat(PixelFormat.TRANSLUCENT);
        isFull = true;
        mLift = moduleContext.optInt("lift", 0);
        mTop = moduleContext.optInt("top", 0);
        mHight = moduleContext.optInt("hight", 100);
        mWidth = moduleContext.optInt("width", -1);
        mId = moduleContext.optInt("mId", -1);
        mFixed = moduleContext.optBoolean("fixed", false);
        mIndexName = moduleContext.optString("indexName", "");
        mFllScreen = moduleContext.optBoolean("fullScreen", false);
        mUri = moduleContext.optString("uri", "http://resource.apicloud.com/video/apicloud3.mp4");
        mMaxProbeTime = moduleContext.optInt("maxprobetime", 2000);
        mImageUri = moduleContext.optString("imageuri", "");
        mListImageWidth = moduleContext.optInt("listImagewidth", 300);
        mListImageHeight = moduleContext.optInt("listImageheight", 500);
        mTitleText = moduleContext.optString("titleText", "标题获取失败");


        mHandImageUri = moduleContext.optInt("videotype", 2);
        //头部图片的背景uri
        mTitleImageUrl = moduleContext.optString("headimageurl", "");
        //是否展示人数
        mShowNumber=moduleContext.optBoolean("shownumber", false);



        mFllFixed = moduleContext.optBoolean("fixedFull", true);
        mIndexFullName = moduleContext.optString("indexFullName", "");
        if (mRela == null) {
            //初始化视频播放器
            mVV = new BDCloudVideoView(getContext());
            mMediaController = new SimpleMediaController(getContext());
            mRela = new RelativeLayout(getContext());
            mRela.setBackgroundColor(Color.BLACK);
        } else {
            removeViewFromCurWindow(mRela);
            mRela.setBackgroundColor(Color.BLACK);
        }
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(-1, -1);
        params.setMargins(mLift, mTop, 0, 0);
        //main
        insertViewToCurWindow(mRela, params, mIndexFullName, mFllFixed);
        initViodView();
    }

    //点击暂停
    public void jsmethod_openPause(UZModuleContext moduleContext) {
        mVV.pause();
    }

    //点击开始图片
    public void jsmethod_openSatrt(UZModuleContext moduleContext) {
        if (!mVV.isPlaying()) {
            mVV.start();
        }
    }

    //点击停止
    public void jsmethod_openStop(UZModuleContext moduleContext) {

        if (mVV.isPlaying()) {
            mVV.stopPlayback();
            mVV.release();
        }
    }

    //点击播放切换播放目录
    public void jsmethod_openNextPlay(UZModuleContext moduleContext) {
        mUri = moduleContext.optString("uri", "rtmp://live.hkstv.hk.lxdns.com/live/hks");
        mHandImageUri = moduleContext.optInt("videotype", 1);
        //头部图片的背景uri
        mTitleImageUrl = moduleContext.optString("headimageurl", "");
        //是否展示人数
        mShowNumber=moduleContext.optBoolean("shownumber", false);


        boolean isPaly = moduleContext.optBoolean("isPlay", true);
        mVV.setVideoPath(mUri);
        //根据地址记录当前的播放次数
        errorTime = 0;
        mMediaController.getSeekBar().setProgress(0);
        //初始化显示标题
        if (mHandImageUri == 1){
            mMediaController.getPlayState().setBackgroundResource(R.drawable.live);
        }else if (mHandImageUri == 2){
            mMediaController.getPlayState().setBackgroundResource(R.drawable.recorded);
        }else if (mHandImageUri == 3){
            mMediaController.getPlayState().setBackgroundResource(R.drawable.video);
        }else if (mHandImageUri == 4){
            Glide.with(getContext())
                    .load(mTitleImageUrl)
                    .placeholder(R.drawable.video)
                    .error(R.drawable.video)
                    .into(mMediaController.getPlayState());
        }else {
            mMediaController.getPlayState().setBackgroundResource(R.drawable.video);

        }
        //是否显示人数
        if (mShowNumber){
            mMediaController.getPeoploNumber().setVisibility(View.VISIBLE);
            mMediaController.getTitleImage().setVisibility(View.VISIBLE);
        }else {
            mMediaController.getPeoploNumber().setVisibility(View.INVISIBLE);
            mMediaController.getTitleImage().setVisibility(View.INVISIBLE);
        }
    //设置是否马上播放
        if (isPaly) {
            mVV.start();
        }else {
            mVV.pause();
        }
    }

    //设置音量
    public void jsmethod_openVolumeSetting(UZModuleContext moduleContext) {

        double mVolume = moduleContext.optDouble("volume", 1.0);
        float nVolume = (float) mVolume;
        //设置声音
        mVV.setVolume(nVolume, nVolume);
        mMediaController.getMusicClose().setSelected(false);
    }

    //设置是否循环
    public void jsmethod_openLooper(UZModuleContext moduleContext) {
        boolean mLooper = moduleContext.optBoolean("looper", false);
        mVV.setLooping(mLooper);
        mVV.start();
    }

    //跳转到指定位置
    public void jsmethod_openSkipPostion(UZModuleContext moduleContext) {

        int mPosition = moduleContext.optInt("position", 1000);
        double mSpeed = moduleContext.optDouble("speed", 1.0);
        int mMaxSize = moduleContext.optInt("maxsizeinbytes", 1024);
        int mMaxProbeSize = moduleContext.optInt("maxprobesize", 1024);

        float speed = (float) mSpeed;
        mVV.seekTo(mPosition);
        mVV.setSpeed(speed);
        mVV.setMaxCacheSizeInBytes(mMaxSize);
        mVV.setMaxProbeSize(mMaxProbeSize);

    }

    //移除视频播放器
    public void jsmethod_removeVido(UZModuleContext moduleContext) {
        if (mRela != null) {
            if (mVV != null) {
                mVV.stopPlayback();// 释放播放器资源
                //                mVV.release();// 释放播放器资源和显示资源,暂时不能放开，全屏的时候会蹦
                //                mVV = null;//不能等于null,不然监听的时候会包空指针
            }
            removeViewFromCurWindow(mRela);
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    //是否显示进度条
    public void jsmethod_showProgress(UZModuleContext moduleContext) {
        boolean isShown = moduleContext.optBoolean("isShown", false);
        //进度条以及进度条的时间
        if (!isShown) {
            mMediaController.getSeekBar().setVisibility(View.INVISIBLE);
            mMediaController.getReadTime().setVisibility(View.INVISIBLE);
            mMediaController.getAllTime().setVisibility(View.INVISIBLE);
        } else {
            mMediaController.getSeekBar().setVisibility(View.VISIBLE);
            mMediaController.getReadTime().setVisibility(View.VISIBLE);
            mMediaController.getAllTime().setVisibility(View.VISIBLE);
        }
    }

    //第一次执行
    public void jsmethod_firstToPlay(UZModuleContext moduleContext) {

        //全局是不是只有一次播放，初始化完成时，只能调用一次
        if (isFristPlay) {
            mVV.start();
        }
        //只有一次有效
        isFristPlay = false;
    }

    //仅仅是提供横竖屏切换(横屏)
    public void jsmethod_transverseScream(UZModuleContext moduleContext) {
        getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        isFull = true;
    }

    //仅仅是提供横竖屏切换(竖屏)
    public void jsmethod_verticalScream(UZModuleContext moduleContext) {
        getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        isFull = false;
    }

    private void initViodView() {
        mMediaController.getShopImage().setVisibility(View.VISIBLE);
        //设置图片的大小
        //        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mMoveImageWidth, mMoveImageHeigh);
        //        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
        //        params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
        //        mMediaController.getSliedBar().setLayoutParams(params);


        //设置侧滑点击事件
        //侧面划入滑出效果
        PropertyValuesHolder animator = PropertyValuesHolder.ofFloat("TranslationX", 0f, -mListImageWidth);
        PropertyValuesHolder animatorw = PropertyValuesHolder.ofFloat("TranslationX", -mListImageWidth, 0.0f);
        mAnimtion = ObjectAnimator.ofPropertyValuesHolder(mMediaController.getSliedBar(), animator, animatorw).setDuration(0);
        mAnimtion.start();


        //侧滑点击事件
        mMediaController.getSliedBar().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCloseOpen) {
                    mAnimtion.start();
                    mMediaController.setListVisible(false, itemBeens, mListImageWidth, mListImageHeight);
                    mMediaController.getShopImage().setVisibility(View.VISIBLE);
                } else {
                    mAnimtion.reverse();
                    mMediaController.getShopImage().setVisibility(View.GONE);
                    mMediaController.setListVisible(true, itemBeens, mListImageWidth, mListImageHeight);
                }
                mCloseOpen = !mCloseOpen;
            }
        });


        //TODO：这里判断是横竖屏，ture为全屏播放
        if (isFull) {
            getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            //切换全屏播放的按钮
            mMediaController.getFullSecream().setSelected(false);
            //侧滑菜单是否显示
            mMediaController.getSliedBar().setVisibility(View.VISIBLE);
            //侧滑菜单是否显示
            mMediaController.getListView().setVisibility(View.INVISIBLE);
        } else {
            getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            //切换全屏播放的按钮
            mMediaController.getFullSecream().setSelected(true);
            //侧滑菜单是否显示
            mMediaController.getSliedBar().setVisibility(View.INVISIBLE);

            //侧滑菜单是否显示
            mMediaController.getListView().setVisibility(View.INVISIBLE);

            if (mAnimtion != null) {
                mAnimtion.start();
                mCloseOpen = false;
            }
        }

        //视频比例和屏幕比例不一致的话，默认不能全屏问题
        if (mFllScreen) {
            //视频占满整个屏幕
            mVV.setVideoScalingMode(BDCloudVideoView.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
        } else {
            //            视频不占满整个屏幕
            mVV.setVideoScalingMode(BDCloudVideoView.VIDEO_SCALING_MODE_SCALE_TO_FIT);
        }
        //保证不息屏
        getContext().getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //设置播放器与播放器播放器所搭载的布局一致
        RelativeLayout.LayoutParams rllp = new RelativeLayout.LayoutParams(-1, -1);
        mRela.removeAllViews();
        mRela.addView(mVV, rllp);
        mRela.addView(mMediaController);
        mVV.setVideoPath(mUri);
        //根据地址记录当前的播放次数
        errorTime = 0;
        initFirstVideo();
        //开始播放，当点击视频前的图片时才能播放
        if (isFristPlay){
            mVV.start();
        }
        //TODO:点击开始和暂停按钮
        mMediaController.getImageStart().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //方式firstToPlay重复调用
                if (mVV.isPlaying()) {
                    mVV.pause();
                    isFristPlay = false;
                } else {
                    mVV.start();
                    isFristPlay = true;
                }
            }
        });

        //TODO:设置进度条的点击事件
        mMediaController.getSeekBar().setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, final int progress, boolean fromUser) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mMediaController.seatProgress(progress);
                    }
                });
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                if (mVV.getDuration() > 0) {
                    int i = (mVV.getDuration() * progress) / 10000;
                    mVV.seekTo(i);
                    seekBar.setEnabled(true);
                } else {
                    seekBar.setEnabled(false);
                }
            }
        });

        //TODO:点击进行横竖屏切换
        mMediaController.getFullSecream().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取全局未捕获的异常
                // CrashHandler crashHandler = CrashHandler.getInstance();
                // crashHandler.init(getContext());
                mMediaController.getShopImage().setVisibility(View.VISIBLE);

                //记录切换前播放的进度
                playPress = mVV.getCurrentPosition();
                removeViewFromCurWindow(mRela);
                if (isFull) {
                    //TODO:先移除布局ture为全屏播放
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mWidth, mHight);
                    params.setMargins(mLift, mTop, 0, 0);
                    //再添加布局
                    insertViewToCurWindow(mRela, params, mIndexName, mFixed);
                    mMediaController.getFullSecream().setSelected(false);
                    isFull = !isFull;
                    //再开始播放
                    //这里仅仅是横竖屏不涉及播放，并且解决返回键没有点击事件的
                    initPlay();
                    JSONObject object = new JSONObject();
                    try {
                        object.put("mIsFull", 2);
                        object.put("mId", mId);
                        //设置为false为不间断的想后台发送数据
                        mModuleContext.success(object, false);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    //先移除布局
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(-1, -1);
                    params.setMargins(0, 0, 0, 0);
                    //再添加布局
                    insertViewToCurWindow(mRela, params, mIndexFullName, mFllFixed);
                    mMediaController.getFullSecream().setSelected(true);
                    isFull = !isFull;
                    //再开始播放
                    //这里仅仅是横竖屏不涉及播放，并且解决返回键没有点击事件的
                    JSONObject object = new JSONObject();
                    try {
                        object.put("mIsFull", 1);
                        object.put("mId", mId);
                        //设置为false为不间断的想后台发送数据
                        mModuleContext.success(object, false);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    initPlay();
                }

            }
        });

        //点击静音
        mMediaController.getMusicClose().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isMusic = !isMusic;
                if (isMusic) {
                    mMediaController.getMusicClose().setSelected(true);
                    mVV.setVolume(0, 0);
                } else {
                    mMediaController.getMusicClose().setSelected(false);
                    mVV.setVolume(1, 1);
                }

            }
        });


        //设置ListVIew的条目点击事件
        mMediaController.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mAnimtion.start();
                mCloseOpen = false;
                mMediaController.getListView().setVisibility(View.INVISIBLE);
                mVV.setVideoPath(itemBeens.get(position).getVidoUri());
                //根据地址记录当前的播放次数
                errorTime = 0;
                mId = Integer.parseInt(itemBeens.get(position).getId());
                mMediaController.getTitleText().setText(itemBeens.get(position).getHandText());
                //                Glide.with(getContext())
                //                        .load(mHandImageUri)
                //                        .placeholder(R.drawable.lively)
                //                        .error(R.drawable.lively)
                //                        .into(mMediaController.getTitleImage());
                if (itemBeens.get(position).getVideotype() == 1){
                    //文字和人数都显示都显示
                    mMediaController.getPlayState().setBackgroundResource(R.drawable.live);
                } else if (itemBeens.get(position).getVideotype() == 2){
                    mMediaController.getPlayState().setBackgroundResource(R.drawable.recorded);
                } else if (itemBeens.get(position).getVideotype() == 3){
                    mMediaController.getPlayState().setBackgroundResource(R.drawable.video);
                }else if (itemBeens.get(position).getVideotype() == 4){
                    Glide.with(getContext())
                            .load(itemBeens.get(position).getImageurl())
                            .placeholder(R.drawable.video)
                            .error(R.drawable.video)
                            .into(mMediaController.getPlayState());

                }else {
                    mMediaController.getPlayState().setBackgroundResource(R.drawable.video);
                }

                //是否显示人数
                if (itemBeens.get(position).getShownumber()){
                    mMediaController.getPeoploNumber().setVisibility(View.VISIBLE);
                    mMediaController.getTitleImage().setVisibility(View.VISIBLE);
                }else {
                    mMediaController.getPeoploNumber().setVisibility(View.INVISIBLE);
                    mMediaController.getTitleImage().setVisibility(View.INVISIBLE);
                }

                mMediaController.getShopImage().setVisibility(View.VISIBLE);
                mVV.start();
            }
        });

        //点击分享
        mMediaController.getShareScream().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JSONObject object = new JSONObject();
                try {
                    object.put("share", 100);
                    object.put("mId", mId);
                    //设置为false为不间断的想后台发送数据
                    mModuleContext.success(object, false);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        //点击购物车
        mMediaController.getShopImage().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JSONObject object = new JSONObject();
                try {
                    object.put("shoping", 200);
                    object.put("mId", mId);
                    //设置为false为不间断的想后台发送数据
                    mModuleContext.success(object, false);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

        mMediaController.getTitleText().setText(mTitleText);
        //初始化显示标题
        if (mHandImageUri == 1){
            mMediaController.getPlayState().setBackgroundResource(R.drawable.live);
        }else if (mHandImageUri == 2){
            mMediaController.getPlayState().setBackgroundResource(R.drawable.recorded);
        }else if (mHandImageUri == 3){
            mMediaController.getPlayState().setBackgroundResource(R.drawable.video);
        }else if (mHandImageUri == 4){
            Glide.with(getContext())
                                    .load(mTitleImageUrl)
                                    .placeholder(R.drawable.video)
                                    .error(R.drawable.video)
                                    .into(mMediaController.getPlayState());
        }else {
            mMediaController.getPlayState().setBackgroundResource(R.drawable.video);

        }
        //是否显示人数
        if (mShowNumber){
            mMediaController.getPeoploNumber().setVisibility(View.VISIBLE);
            mMediaController.getTitleImage().setVisibility(View.VISIBLE);
        }else {
            mMediaController.getPeoploNumber().setVisibility(View.INVISIBLE);
            mMediaController.getTitleImage().setVisibility(View.INVISIBLE);
        }
        //只有初始化的时候是可以播放的
        isFristPlay = true;

    }

    private void initFirstVideo() {
        mVV.setMaxProbeTime(mMaxProbeTime); // 设置首次缓冲的最大时长
        mVV.setTimeoutInUs(1000000);

        //播放器准备好的监听
        mVV.setOnPreparedListener(this);
        mVV.setOnCompletionListener(this);

        //播放错误监听
        mVV.setOnErrorListener(this);
        //播放信息监听
        mVV.setOnInfoListener(this);

        //该方法主要用于进度条的监听
        mVV.setOnBufferingUpdateListener(this);
        //播放状态监听，主要用于进度条的监听
        mVV.setOnPlayerStateListener(this);
    }

    private void initPlay() {
        if (isFull) {
            getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            //切换全屏播放的按钮
            mMediaController.getFullSecream().setSelected(false);
            //侧滑菜单是否显示
            mMediaController.getSliedBar().setVisibility(View.VISIBLE);
            //侧滑菜单是否显示
            mMediaController.getListView().setVisibility(View.INVISIBLE);
        } else {
            getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            //切换全屏播放的按钮
            mMediaController.getFullSecream().setSelected(true);
            //侧滑菜单是否显示
            mMediaController.getSliedBar().setVisibility(View.INVISIBLE);
            //侧滑菜单是否显示
            mMediaController.getListView().setVisibility(View.INVISIBLE);
            if (mAnimtion != null) {
                mAnimtion.start();
                mCloseOpen = false;
            }

        }
        //这里的释放资源是指在切换屏幕的时候会有其他图片或音像遮挡
        mVV.release();

        initWithViode();
        //跳转到指定的进度
        mVV.start();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mVV.seekTo(playPress);
                    }
                });
            }
        }, 300);
        System.out.println("进来这边了=="+playPress);
    }

    private void initWithViode() {
        mVV.setMaxProbeTime(mMaxProbeTime); // 设置首次缓冲的最大时长
        mVV.setTimeoutInUs(1000000);

        //播放器准备好的监听
        mVV.setOnPreparedListener(this);
        mVV.setOnCompletionListener(this);

        //播放错误监听
        mVV.setOnErrorListener(this);
        //播放信息监听
        mVV.setOnInfoListener(this);

        //该方法主要用于进度条的监听
        mVV.setOnBufferingUpdateListener(this);
        //播放状态监听，主要用于进度条的监听
        mVV.setOnPlayerStateListener(this);
    }

    @Override
    public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
        mHandler.removeCallbacksAndMessages(null);
        errorTime++;
        if (errorTime>=6){
            Toast.makeText(getContext(),"当前视频播放失败，请观看其他视频",Toast.LENGTH_SHORT).show();
        }else {
            mVV.seekTo(playPress);
            mVV.start();
        }
        return false;
    }
    @Override
    public boolean onInfo(IMediaPlayer iMediaPlayer, int i, int i1) {
        return false;
    }

    @Override
    public void onBufferingUpdate(IMediaPlayer iMediaPlayer, int percent) {
        if (mMediaController != null && mVV != null) {
            final long currentPosition = mVV.getCurrentPosition();
            final long duration = mVV.getDuration();
            //TODO:设置更细化的进度
            if (currentPosition > 0 && duration > 0) {
                long pos = 10000L * currentPosition / duration;
                mMediaController.seatProgress((int) pos);
                mMediaController.getSeekBar().setEnabled(true);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mMediaController.getReadTime().setText(formatMilliSecond((int) currentPosition));
                        mMediaController.getAllTime().setText(formatMilliSecond((int) duration));
                    }
                });
            } else {
                mMediaController.getSeekBar().setEnabled(false);
            }
        }
        JSONObject object = new JSONObject();
        try {
            object.put("currentposition", iMediaPlayer.getCurrentPosition());
            object.put("duration", iMediaPlayer.getDuration());
            object.put("mId", mId);
            if (isFull) {
                object.put("mIsFull", 1);
            } else {
                object.put("mIsFull", 2);
            }
            //设置为false为不间断的想后台发送数据
            mModuleContext.success(object, false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPlayerStateChanged(PlayerState nowState) {
        PlayerState state = mVV.getCurrentPlayerState();
        if (state == PlayerState.STATE_IDLE || state == PlayerState.STATE_ERROR) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    int currentPosition = mVV.getCurrentPosition();
                    int duration = mVV.getDuration();
                    mMediaController.getReadTime().setText(formatMilliSecond(currentPosition));
                    mMediaController.getAllTime().setText(formatMilliSecond(duration));
                }
            });
            //播放监听
        } else if (state == PlayerState.STATE_PLAYING) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mHandler.sendEmptyMessage(2);
                    mHandler.postDelayed(this, 1000);
                }
            }, 1000);
        } else if (state == PlayerState.STATE_PAUSED || state == PlayerState.STATE_IDLE) {
            mHandler.sendEmptyMessage(1);
        } else if (state == PlayerState.STATE_PREPARED) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mHandler.sendEmptyMessage(2);
                    mHandler.postDelayed(this, 1000);
                }
            }, 1000);

        }
    }

    private String formatMilliSecond(int milliSecond) {
        int seconds = milliSecond / 1000;
        int hh = seconds / 3600;
        int mm = seconds % 3600 / 60;
        int ss = seconds % 60;
        String strTemp = null;
        if (0 != hh) {
            strTemp = String.format("%02d:%02d:%02d", hh, mm, ss);
        } else {
            strTemp = String.format("%02d:%02d", mm, ss);
        }
        return strTemp;
    }


    public void jsmethod_showPeopleNumber(UZModuleContext moduleContext) {
        mPeoploNumber = moduleContext.optString("peopleNumber", "999人在线");
        mMediaController.getPeoploNumber().setText(mPeoploNumber);

    }

    @Override
    public void onPrepared(IMediaPlayer iMediaPlayer) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(2);
                mHandler.postDelayed(this, 1000);
            }
        }, 1000);
    }

    @Override
    public void onCompletion(IMediaPlayer iMediaPlayer) {

        System.out.println("准备完成");
    }
}
